package com.fc.mall.portal.service.impl;

import com.fc.mall.exception.InternalServerErrorException;
import com.fc.mall.portal.service.ConfigService;
import com.fc.mall.portal.service.SysPropertyConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ConfigServiceImpl implements ConfigService {

    @Autowired
    private SysPropertyConfigService sysPropertyConfigService;

    @Override
    public boolean getRequiredBooleanConfig(String code) {
        String value = getRequiredConfig(code);
        try {
            return value.equals("1");
        } catch (NumberFormatException e) {
            throw new InternalServerErrorException(String.format("配置不是Boolean: %s", code));
        }
    }

    @Override
    public boolean getOptionalBooleanConfig(String code, boolean defaultValue) {
        try {
            String value = getConfig(code);
            return value == null ? defaultValue : Boolean.parseBoolean(value);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    @Override
    public int getRequiredIntConfig(String code) {
        String value = getRequiredConfig(code);
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            throw new InternalServerErrorException(String.format("配置不是Integer: %s", code));
        }
    }

    @Override
    public int getOptionalIntConfig(String code, int defaultValue) {
        try {
            String value = getConfig(code);
            return value == null ? defaultValue : Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    @Override
    public long getRequiredLongConfig(String code) {
        String value = getRequiredConfig(code);
        try {
            return Long.parseLong(value);
        } catch (NumberFormatException e) {
            throw new InternalServerErrorException(String.format("配置不是Long: %s", code));
        }
    }

    @Override
    public long getOptionalLongConfig(String code, long defaultValue) {
        try {
            String value = getConfig(code);
            return value == null ? defaultValue : Long.parseLong(value);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    @Override
    public String getRequiredConfig(String code) {
        String value = getConfig(code);
        if (value != null) {
            return value;
        }
        throw new InternalServerErrorException(String.format("找不到配置: %s", code));
    }

    @Override
    public String getOptionalConfig(String code, String defaultValue) {
        String value = getConfig(code);
        return value == null ? defaultValue : value;
    }

    private String getConfig(String code) {
        return sysPropertyConfigService.getSysConfigValueByKey(code);
    }
}
